package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.user.dto.ApAuthor;
import com.heima.user.dto.AuthDto;
import com.heima.user.dto.WmUser;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserRealname;
import com.heima.user.feign.ArticleClient;
import com.heima.user.feign.MediaClient;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.IApUserRealnameService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.user.service.IApUserService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * APP实名认证信息表 服务实现类
 * </p>
 *
 * @author jinze
 * @since 2022-08-07
 */
@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements IApUserRealnameService {

    @Autowired
    private IApUserService userService;

    @Autowired
    private MediaClient mediaClient;

    @Autowired
    private ArticleClient articleClient;


    @Override
    //按照状态查询用户认证列表
    public ResponseResult<List<ApUserRealname>> userListPage(AuthDto dto) {

        // 进行分页查询
        // 构建分页条件
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        // 构建查询条件
        LambdaQueryWrapper<ApUserRealname> query = new LambdaQueryWrapper<>();
        // 根据状态进行查询
        if (dto.getStatus() != null) {
            query.eq(ApUserRealname::getStatus, dto.getStatus());
        }
        IPage<ApUserRealname> iPage = this.page(page, query);
        // 构建通用的分页响应
        return new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
    }


    @Override
    //判断审核状态
    @GlobalTransactional
    public ResponseResult auth(AuthDto dto, int status) {
        // 判断用户审核失败 status = 0
        // 修改认证表状态为2 审核失败,记录驳回原因
        // 根据认证id查询认证表
        // 若审核失败，返回原因，返回错误信息
        // 若审核成功，查询用注册信息，创建自媒体用户（WmUser），创建作者（Author），更新作者信息
        // 返回空
        ApUserRealname apUserRealname = this.getById(dto.getId());
        if (status==0){
            apUserRealname.setStatus(2);
            apUserRealname.setReason(dto.getReason());
            this.updateById(apUserRealname);
        }else {

            ApUser user = userService.getById(apUserRealname.getUserId());
            // 创建自媒体用户
            WmUser wmUser = createMediaUser(user);
            // 创建文章作者
            if (wmUser != null) {
                ApAuthor apAuthor = createAuthor(user, wmUser);
                if (apAuthor != null) {
                    // 更新自媒体账号中的作者id
                    wmUser.setApAuthorId(apAuthor.getId());
                    mediaClient.updateMediaUser(wmUser);
                    // 更新认证表的状态为9 审核通过
                    apUserRealname.setStatus(9);
                    this.updateById(apUserRealname);
                    // 更新用户注册表中的标识为 1 自媒体人
                    user.setFlag(1);
                    userService.updateById(user);
                }
            }
        }
        return ResponseResult.okResult();
    }

    private ApAuthor createAuthor(ApUser user, WmUser wmUser) {
        // 构建作者信息
        ApAuthor author = new ApAuthor();
        author.setName(user.getName());
        author.setType(2);
        author.setUserId(user.getId());
        author.setWmUserId(wmUser.getId());
        ResponseResult<ApAuthor> responseResult = articleClient.saveArticleAuthor(author);
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApAuthor apAuthor = responseResult.getData();
            return apAuthor;
        } else {
            throw new RuntimeException("调用文章服务失败");
        }
    }

    private WmUser createMediaUser(ApUser user) {
        WmUser wmUser = new WmUser();
        // 基本属性从apUser赋值
        BeanUtils.copyProperties(user, wmUser);
        wmUser.setId(null);
        wmUser.setApUserId(user.getId());
        wmUser.setNickname(user.getName());
        wmUser.setStatus(9);
        wmUser.setType(0);
        ResponseResult<WmUser> responseResult = mediaClient.saveMediaUser(wmUser);
        // 判断远程调用的结果
        if (responseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            WmUser wmUser1 = responseResult.getData();
            return wmUser1;
        }
        return null;
    }
}
